const formidable = require("formidable")
const express = require("express")
const path = require("path")
const route = express.Router()
const isLoginMiddel = require("../middleware/isLoginMiddel")
const advModel = require("../db/model/addAdvModel")

route.put("/updateAdv", isLoginMiddel, async (req, res) => {
    const _id=req.query
    //formidable.IncomingForm方法实例化的对象可以解析formData格式的数据，实例化的时候可以传入一些配置
    const form = new formidable.IncomingForm({
        uploadDir: path.resolve(__dirname, "../upload"),
        keepExtensions: true
    });
    //解析req中携带的数据
    form.parse(req, async (err, params, file) => {
        //params就是除了文件之外的数据组成的对象
        const {
            advTitle,
            advType,
            advOrder
        } = params;
        //file就是文件的信息
        // console.log(file.advPic.newFilename);
        //添加数据库
        try {
            await advModel.updateOne({_id},{
                advTitle,
                advType,
                advOrder,
                advHref: "/upload/" + file.advPic.newFilename,
                addTime: new Date().toLocaleString()
            })
            res.send({
                code: 10000,
                msg: "更新成功",
                data: null
            })
        } catch (e) {
            res.send({
                code: 10001,
                msg: "更新广告信息到服务器异常" + e.message,
                data: null
            })
        }
    })

})

module.exports = route